<template>
    <ZZDialog class='settings' title='我的标记' @close='callbackClose()'>
        <el-upload :file-list="fileList" class="upload-demo" accept="" :on-change="handleChange" v-show="false">
            <template #trigger>
                <el-button type="primary" ref="updata">select file</el-button>
            </template>
        </el-upload>
        <div class="mp_head">
            <ul>
                <li @click="drawPoint()"><i class="fa fa-edit" title="添加注记"></i></li>
                <li class="ml10">|</li>
                <li @click="openfile1()"><i class="fa fa-folder-open-o" title="打开文件"></i></li>
                <li @click="openfile2()"><i class="fa fa-folder-open" title="叠加文件"></i></li>
                <li @click="savefile()"><i class="fa fa-save" title="保存文件"></i></li>
                <li class="ml10">|</li>
                <li @click="deleteAll()"><i class="fa fa-trash" title="清空标记"></i></li>
                <li @click="isplotedit()"><i :class="classeidt" title="是否可编辑"></i></li>
            </ul>
        </div>

        <el-table :data="tableData" row-key="name" style="width: 100%,min-height:200px;max-height:600px;"
            highlight-current-row   @row-dblclick="handleCurrentChange">
            <el-table-column prop="id" label="id" v-if="false" />
            <el-table-column fixed prop="name" label="名称" sortable column-key="name" />
            <el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleClick(scope.row.id)"><i class="fa fa-trash"
                            title="删除"></i></el-button>
                </template>
            </el-table-column>
        </el-table>
    </ZZDialog>
</template>

<script>
import { LocalStorageUser } from '../../../utils/localStorage'
import { DateFormat } from '../../../utils/dateFormat'
import ZZDialog from '../../../common/ZZDialog.vue'
import markerpng from './img/marker.png'
export default{
    components:{
        ZZDialog
    },
    data(){
        return{
            viewer:undefined,
            drawControl: null,
            editable: true,
            classeidt:'fa fa-unlock',
            isClearForOpenFile:false,
            label_font_style:"normal small-caps normal 19px 楷体",
            storageName:"wisemapgis_addmarker",
            fileList:[],
            tableData :[{ id: "0", name: "", remark: "" }]
        }
    },
    beforeMount(){
        this.viewer = this.$store.state.viewer
    },
    mounted(){
        window.drawControl = new zz3d.Draw(this.viewer, {
        hasEdit: false,
    });

    //事件监听  
    window.drawControl.on(zz3d.draw.event.DrawCreated, (e)=>{
        var entity = e.entity;
        this.bindMarkerEx(entity);
    });
    window.drawControl.on(zz3d.draw.event.EditMovePoint,  (e)=> {//编辑修改了点
        var entity = e.entity;
        this.saveEntity(entity, "");
    });
    this.getList();
    },
    methods:{
        clearPlotFile  () {
            this.fileList.slice(0)
        },
        handleChange(uploadFile) {
            this.fileList = this.fileList.slice(-3)
            var fileName = uploadFile.name;
            var fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)).toLowerCase();
            if (fileType != "json") {
                this.clearPlotFile();
                return;
            }
            var reader = new FileReader();
            reader.readAsText(uploadFile.raw, 'UTF-8');
            reader.onloadend =  (e)=>{
                var strjson = JSON.parse(e.target?.result);
                this.jsonToLayer(strjson, this.isClearForOpenFile);
                this.clearPlotFile();
            };

        },
        hasEdit (val) {
            this.editable = val;
            window.drawControl.hasEdit(val);
        },
        openfile1 () {
            this.isClearForOpenFile = true
            this.$refs.updata.$el.click()
        },
        openfile2  () {
            this.isClearForOpenFile = false
            this.$refs.updata.$el.click()
        },
        savefile () {
            let data = this.getJsonData();
            var blob = new Blob([data]);
            var aLink = document.createElement('a');
            aLink.download = "fileName.json";
            aLink.href = URL.createObjectURL(blob);
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
        },
        isplotedit () {
            this.editable = !this.editable;
            if (this.editable) {
                this.classeidt = 'fa fa-unlock'
            }
            else {
                this.classeidt = 'fa fa-lock'
            }
            this.hasEdit(this.editable);
        },
        drawPoint () {
            window.drawControl.stopDraw();
            window.drawControl.startDraw({
                type: "billboard",
                style: {
                    scale: 1,
                    image: markerpng
                }
            });
        },
        bindMarkerEx (entity) {
            if (entity == null || entity.position == null) return;
            entity.attribute.attr = entity.attribute.attr || {};
            entity.attribute.attr.id = 0;//(new Date()).format("yyyyMMddHHmmss");
            entity.attribute.attr.name = "我的标记";
            entity.label = this.getLabelStyle(entity.attribute.attr.name);
            entity.billboard.scaleByDistance = new Cesium.NearFarScalar(1.5e2, 1, 8.0e6, 0.2);
            
            this.saveEntity(entity,  ()=> {
                entity.popup = {
                    html:  (entity1)=> {
                        return this.getMarkerInhtml(entity1.attribute.attr);
                    },
                    anchor: [0, -35],
                    clickcallback:  ()=> {
                        let addmaker = document.getElementById("addmarker_save")  || null;
                        addmaker?.addEventListener('click', this.saveEditFeature)

                        let delmaker = document.getElementById("addmarker_del") || null;
                        delmaker?.addEventListener('click', this.deleteEditFeature)
                    }
                };

                this.viewer.zz.popup.show(entity, entity.position._value);
            });
        },
        saveEditFeature () {
            let id = Number((document.getElementById("addmarker_attr_id") )?.value);
            let name = (document.getElementById("addmarker_attr_name") )?.value;
            let remark = (document.getElementById("addmarker_attr_remark"))?.value;
            var entity = window.drawControl.getEntityById(id);

            entity.attribute.attr = entity.attribute.attr || {};
            entity.attribute.attr.name = name//$.trim($("#addmarker_attr_name").val());
            entity.attribute.attr.remark = remark // proxy.$refs.remark.$el.value//$.trim($("#addmarker_attr_remark").val());

            this.viewer.zz.popup.close();
            entity.label.text = entity.attribute.attr.name;

            this.saveEntity(entity, "");
            this.getMarkerDataList()
        },
        deleteEditFeaturebyid (id) {
            var entity = window.drawControl.getEntityById(id);
            window.drawControl.deleteEntity(entity);

            this.viewer.zz.popup.close();

            {//浏览器本地存储 
                var storagedata = this.getJsonData();
                LocalStorageUser.add(this.storageName, storagedata);
            }
            this.getMarkerDataList()
        },
        deleteEditFeature () {
            let id = (document.getElementById("addmarker_attr_id"))?.value;
            var entity = window.drawControl.getEntityById(id);
            window.drawControl.deleteEntity(entity);

            this.viewer.zz.popup.close();

            {//浏览器本地存储 
                var storagedata = this.getJsonData();
                LocalStorageUser.add(this.storageName, storagedata);
            }
            this.getMarkerDataList()
        },
        getMarkerInhtml (attr) {
            var inhtml;
            if (this.editable) {
                if (!attr.name || attr.name == "我的标记")
                    attr.name = "";
                if (!attr.remark)
                    attr.remark = "";
                if (!attr.id)
                    attr.id = "0";
                inhtml = '<div class="addmarker-popup-titile">添加标记</div><div class="addmarker-popup-content" ><form >' +
                    ' <input type="text" id="addmarker_attr_id" class="form-control" style="display:none" value="' + attr.id + '"  /> </div>' +
                    '<div class="form-group"  style="margin:10px;">  <label for="addmarker_attr_name">名称:&nbsp;&nbsp; </label><input type="text" id="addmarker_attr_name" class="form-control" value="' + attr.name + '" placeholder="请输入标记名称"    /> </div>' +
                    '<div class="form-group" style="margin:10px;">  <label for="addmarker_attr_remark">备注:&nbsp;&nbsp; </label><textarea id="addmarker_attr_remark" class="form-control" rows="3" style="resize: none;" placeholder="请输入备注（可选填）"   >' + attr.remark + '</textarea></div>' +
                    '<div class="form-group" style="text-align: center; "><input style="cursor: pointer;" type="button" class="btn btn-primary  btn-sm" value="保存" id="addmarker_save">&nbsp;&nbsp;<input type="button" style="cursor: pointer;"  class="btn btn-danger  btn-sm" value="删除" id="addmarker_del" /></div>' +
                    '</form></div>';
            } else {
                inhtml = '<div class="addmarker-popup-titile">我的标记</div><div class="addmarker-popup-content" ><form >' +
                    '<div class="form-group"><label>名称</label>：' + attr.name + '</div>' +
                    '<div class="form-group"><label>备注</label>：' + attr.remark + '</div>' +
                    '</form></div>';
            }
            return inhtml;
        },
        centerAt (id) {
            var entity = window.drawControl.getEntityById(id);
            if (entity) {
                //参数解释：点数据：radius控制视距距离
                this.viewer.zz.flyTo(entity, { radius: 2500 });
            }
        },
        deleteAll () {
            window.drawControl.deleteAll();
            {//浏览器本地存储 
                //本地存储
                LocalStorageUser.del(this.storageName);
            }
            this.getMarkerDataList()
        },
        getLabelStyle (name) {
            return new Cesium.LabelGraphics({
                text: name == "" ? "我的标记" : name,
                font: this.label_font_style,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 3,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, -50),
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000)
            });
        },
        getJsonData() {
            var arr = [];
            var arrEntity = window.drawControl.getEntitys();
            for (var i = 0, len = arrEntity.length; i < len; i++) {
                var entity = arrEntity[i];
                var attr = entity.attribute.attr;
                var coord = zz3d.draw.attr.billboard.getCoordinates(entity);

                var item = {
                    id: attr.id,
                    name: attr.name,
                    remark: attr.remark,
                    x: coord[0][0],
                    y: coord[0][1],
                    z: coord[0][2]
                };
                arr.push(item);
            }
            return JSON.stringify(arr);
        },
        jsonToLayer (arr, isclear) {
            if (arr == null || arr.length == 0) return;
            if (isclear) {
                window.drawControl.deleteAll();
            }
            var arrEntity = [];
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i];
                if (!item.x || !item.y) continue;

                var attribute = {
                    type: "billboard",
                    attr: {
                        id: item.id || "",
                        name: item.name || "",
                        remark: item.remark || ""
                    },
                    style: {
                        scale: 1,
                        image: markerpng
                    }
                };

                if (!isclear) { //叠加时，清除已有同id数据
                    var entity1 = window.drawControl.getEntityById(attribute.attr.id);
                    window.drawControl.deleteEntity(entity1);
                }

                var position = Cesium.Cartesian3.fromDegrees(item.x, item.y, item.z || 0.0);
                var entity = window.drawControl.attributeToEntity(attribute, position);
                entity.popup = {
                    html:  (entity)=> {
                        return this.getMarkerInhtml(entity.attribute.attr);
                    },
                    anchor: [0, -35]
                };
                entity.billboard.scaleByDistance = new Cesium.NearFarScalar(1.5e2, 1, 8.0e6, 0.2);
                entity.label = this.getLabelStyle(attribute.attr.name);
                arrEntity.push(entity);
            }
            this.getMarkerDataList()
            this.viewer.flyTo(arrEntity, { duration: 2.0 });
        },
        getMarkerDataList() {
            this.tableData.length = 0
            var arrEntity = window.drawControl.getEntitys();
            for (var i = 0, len = arrEntity.length; i < len; i++) {
                if (!arrEntity[i].attribute.attr.name) arrEntity[i].attribute.attr.name = "我的标记";
                this.tableData.push(arrEntity[i].attribute.attr);
            }
        },
        getList () {
            {//读取本地存储
                var laststorage = LocalStorageUser.get(this.storageName); //读取localStorage值  
                if (laststorage != null && laststorage != 'null') {

                    var arr = JSON.parse(laststorage);

                    this.jsonToLayer(arr, true);
                }
            }
            this.getMarkerDataList()
        },
        saveEntity (entity, endfun) {
            {//浏览器本地存储
                if (entity.attribute.attr.id == "0")
                    entity.attribute.attr.id = DateFormat(new Date().toString(), "yyyyMMddhhmmss");
                
                var storagedata = this.getJsonData();
                LocalStorageUser.add(this.storageName, storagedata);

                if (endfun) endfun();
            }
        },
        callbackClose () {
            window.drawControl.deleteAll();
            this.$emit('close')
        },
        handleCurrentChange (val) {
            console.log(val.name)
            this.centerAt(val.id)
        },
        findname(val) {
            return val.name
        },
        handleClick(id) {
            this.deleteEditFeaturebyid(id)
        }
    }
}
</script>
<style scoped>
.settings {
    position: absolute;
    top: 100px;
    width: 280px;
    right: 200px;
}

.mp_head {
    line-height: 35px;
    border-bottom: #dedede 1px solid;
    overflow: hidden;

    ul {
        padding: 0;

        li {
            padding: 0;
            float: left;
            display: inline-block;

            i {
                width: 28px;
                height: 25px;
                line-height: 25px;
                text-align: center;
                border: #dedede 1px solid;
                display: inline-block;
                font-size: 16px;
                margin-left: 10px;
                cursor: pointer;
            }
        }
    }
}

.ml10 {
    margin-left: 10px
}

.mp_head2 {
    width: 100%;
    height: 45px;
    line-height: 45px;
    text-align: center;
}

.dark .mp_head ul li i {
    background-color: rgba(63, 72, 84, 0.6);
    border: #dedede 1px solid;
    color: #ffffff;
}

.addmarker-popup-titile {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    border-radius: 3px 3px 0 0;
    padding: 0 80px 0 20px;
    height: 42px;
    line-height: 42px;
    font-size: 16px;
    color: white;
    background-color: #20a0ff;
    border-bottom: 1px solid #eee;
    overflow: hidden;
}

.addmarker-popup-content {
    width: 260px;
    margin-top: 52px;
    font-size: 14px;
}
.el-table{
    color: #ffffff;
}
.hover-row {
    color: #dedede !important;
}
.current-row{
    color: #dedede !important;
}
</style>